package com.heba.greenmulu.diary;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.product.ItemProductSimilarObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 添加产品
 * Created by jason on 2020/1/22.
 */
public class ItemDiaryProductAddActivity extends BaseActivity {

    private EditText et_search;
    private ImageView iv_scan;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<ItemProductSimilarObject> productSimilarObjectList;

    private String keyWord = "";

    private String barcode = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_product_add);
        EventBus.getDefault().register(this);
        initTopbar();
        findViewById();
        initView();
        getProductSimilarData();
    }

    @Override
    protected void findViewById() {
        et_search = findViewById(R.id.et_search);
        iv_scan = findViewById(R.id.iv_scan);
        recyclerView = findViewById(R.id.recyclerView);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.diary_product));

        productSimilarObjectList = new ArrayList<>();

        recycleAdapter = new QuickAdapter<ItemProductSimilarObject>(productSimilarObjectList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_diary_product;
            }

            @Override
            public void convert(VH holder, ItemProductSimilarObject data, int position) {
                ImageView iv_product = holder.getView(R.id.iv_product);
                TextView tv_product = holder.getView(R.id.tv_product);
                TextView tv_content = holder.getView(R.id.tv_content);
                TextView tv_weight = holder.getView(R.id.tv_weight);

                GlideUtil.loadImageWithDefaultPlaceHolder(ItemDiaryProductAddActivity.this, data.getIcon(), iv_product);
                tv_product.setText(data.getProductName());
                tv_content.setText(data.getBrandName());
                tv_weight.setText(String.format(getResources().getString(R.string.per_serving_size), data.
                        getPackageSize(), data.getPackageUnit(), CommonUtils.subZeroAndDot(data.getServingSize()), data.getServingSizeUnit()));

                /**
                 * eventBus傳遞數據顯示產品
                 */
                holder.itemView.setTag(data);
                holder.itemView.setOnClickListener(v -> {
                    ItemProductSimilarObject object = (ItemProductSimilarObject) v.getTag();
                    MessageEvent event = new MessageEvent();
                    event.setEvent(CommonConfig.PRODUCT_OBJECT);
                    event.setProductSimilarObject(object);
                    EventBus.getDefault().post(event);
                    finishActivity();
                });
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        /**
         * 搜索相關產品
         */
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyWord = et_search.getText().toString();
                    getProductSimilarData();
                }
                return false;
            }
        });

        /**
         * 掃描產品
         */
        iv_scan.setOnClickListener(v -> openActivity(ItemDiaryScanProductActivity.class));

        /**
         * 監聽rv滑動
         */
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    DensityUtils.hideSoftWindow(ItemDiaryProductAddActivity.this, et_search);
                }
            }
        });
    }

    /**
     * 獲取相關產品數據
     */
    private void getProductSimilarData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Keyword", keyWord);
        params.put("Barcode", barcode);
        client.get(Cfg.BaseUrl + "/Diary/SearchProduct", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        productSimilarObjectList.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemProductSimilarObject> itemProductSimilarObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemProductSimilarObject>>() {
                                }.getType());
                                productSimilarObjectList.addAll(productSimilarObjectList.size(), itemProductSimilarObjects);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * 接收EventBus
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收掃描的條形碼code
         */
        if (event.getEvent().equals(CommonConfig.SCAN_PRODUCT_CODE)) {
            keyWord = "";
            barcode = event.getProductCode();
            et_search.setText(barcode);
            getProductSimilarData();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
